<template>
  <el-dialog
    :title="`${dataSource?.name} - 数据结构`"
    v-model="dialogVisible"
    width="800px"
  >
    <div class="table-container" v-loading="loading">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="数据表" name="tables">
          <el-input
            v-model="searchQuery"
            placeholder="搜索表名"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-table :data="filteredTables" style="width: 100%">
            <el-table-column prop="name" label="表名" min-width="200">
              <template #default="{ row }">
                <div class="table-name">
                  <el-icon><Grid /></el-icon>
                  <span>{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="comment" label="注释" min-width="200" />
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button-group>
                  <el-button
                    type="primary"
                    link
                    @click="handleViewStructure(row)"
                  >
                    查看结构
                  </el-button>
                  <el-button type="primary" link @click="handleViewData(row)">
                    查看数据
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="视图" name="views">
          <el-input
            v-model="searchQuery"
            placeholder="搜索视图名"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-table :data="filteredViews" style="width: 100%">
            <el-table-column prop="name" label="视图名" min-width="200">
              <template #default="{ row }">
                <div class="table-name">
                  <el-icon><View /></el-icon>
                  <span>{{ row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="comment" label="注释" min-width="200" />
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button-group>
                  <el-button
                    type="primary"
                    link
                    @click="handleViewStructure(row)"
                  >
                    查看结构
                  </el-button>
                  <el-button type="primary" link @click="handleViewData(row)">
                    查看数据
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 表结构对话框 -->
    <el-dialog
      v-model="structureVisible"
      :title="`${currentTable?.name} - 表结构`"
      width="900px"
      append-to-body
    >
      <el-table :data="currentStructure" style="width: 100%">
        <el-table-column prop="name" label="字段名" min-width="150" />
        <el-table-column prop="type" label="类型" width="120" />
        <el-table-column prop="nullable" label="允许空" width="80">
          <template #default="{ row }">
            <el-tag :type="row.nullable ? 'info' : 'danger'" size="small">
              {{ row.nullable ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="key" label="键" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.key === 'PRI'" type="danger" size="small">
              主键
            </el-tag>
            <el-tag v-else-if="row.key === 'UNI'" type="warning" size="small">
              唯一
            </el-tag>
            <el-tag v-else-if="row.key === 'MUL'" type="info" size="small">
              索引
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="default" label="默认值" width="120" />
        <el-table-column prop="comment" label="注释" min-width="200" />
      </el-table>
    </el-dialog>

    <!-- 表数据对话框 -->
    <el-dialog
      v-model="dataVisible"
      :title="`${currentTable?.name} - 数据预览`"
      width="90%"
      append-to-body
    >
      <div class="data-preview" v-loading="previewLoading">
        <el-table
          :data="previewData"
          style="width: 100%"
          height="500"
          :cell-class-name="cellClassName"
        >
          <el-table-column
            v-for="col in previewColumns"
            :key="col.prop"
            :prop="col.prop"
            :label="col.label"
            :width="col.width"
          />
        </el-table>
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { Search, Grid, View } from "@element-plus/icons-vue";
import type { DataSource } from "@/types/dataSource";
import {
  getTableList,
  getTableStructure,
  getTableData,
} from "@/api/dataSource";

const props = defineProps<{
  visible: boolean;
  dataSource?: DataSource;
}>();

const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
}>();

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit("update:visible", val),
});

const loading = ref(false);
const activeTab = ref("tables");
const searchQuery = ref("");
const tables = ref<any[]>([]);
const views = ref<any[]>([]);

// 结构预览相关
const structureVisible = ref(false);
const currentTable = ref<any>(null);
const currentStructure = ref<any[]>([]);

// 数据预览相关
const dataVisible = ref(false);
const previewLoading = ref(false);
const previewData = ref<any[]>([]);
const previewColumns = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

const filteredTables = computed(() => {
  if (!searchQuery.value) return tables.value;
  const query = searchQuery.value.toLowerCase();
  return tables.value.filter(
    (table) =>
      table.name.toLowerCase().includes(query) ||
      table.comment?.toLowerCase().includes(query)
  );
});

const filteredViews = computed(() => {
  if (!searchQuery.value) return views.value;
  const query = searchQuery.value.toLowerCase();
  return views.value.filter(
    (view) =>
      view.name.toLowerCase().includes(query) ||
      view.comment?.toLowerCase().includes(query)
  );
});

const loadTables = async () => {
  if (!props.dataSource?.id) return;

  loading.value = true;
  try {
    const result = await getTableList(props.dataSource.id);
    tables.value = result.tables;
    views.value = result.views;
  } catch (error) {
    console.error("加载表结构失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleViewStructure = async (table: any) => {
  if (!props.dataSource?.id) return;

  currentTable.value = table;
  structureVisible.value = true;

  try {
    const structure = await getTableStructure(props.dataSource.id, table.name);
    currentStructure.value = structure;
  } catch (error) {
    console.error("加载表结构失败:", error);
  }
};

const handleViewData = async (table: any) => {
  if (!props.dataSource?.id) return;

  currentTable.value = table;
  dataVisible.value = true;
  currentPage.value = 1;
  await loadPreviewData();
};

const loadPreviewData = async () => {
  if (!props.dataSource?.id || !currentTable.value) return;

  previewLoading.value = true;
  try {
    const result = await getTableData(
      props.dataSource.id,
      currentTable.value.name,
      {
        page: currentPage.value,
        pageSize: pageSize.value,
      }
    );

    previewData.value = result.list;
    total.value = result.total;

    if (result.list.length > 0) {
      // 根据第一行数据生成列配置
      previewColumns.value = Object.keys(result.list[0]).map((key) => ({
        prop: key,
        label: key,
        width: key.length * 15 + 80,
      }));
    }
  } catch (error) {
    console.error("加载数据预览失败:", error);
  } finally {
    previewLoading.value = false;
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadPreviewData();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadPreviewData();
};

const cellClassName = ({ row, column }: { row: any; column: any }) => {
  const value = row[column.property];
  if (value === null) return "cell-null";
  return "";
};

watch(
  () => props.visible,
  (val) => {
    if (val) {
      loadTables();
    }
  }
);
</script>

<style scoped>
.table-container {
  min-height: 400px;
}

.search-input {
  margin-bottom: 16px;
  width: 300px;
}

.table-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.data-preview {
  min-height: 500px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.cell-null) {
  color: #909399;
  font-style: italic;
}
</style> 